package com.example.myapplication;

import android.os.Bundle;
import android.content.Intent;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {

    private BlockTimeChecker blockTimeChecker;
    private ParentalControlRepository parentalControlRepository;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // 初始化检查器
        blockTimeChecker = new BlockTimeChecker(this);
        parentalControlRepository = ParentalControlRepository.getInstance(this);
        
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(android.R.id.content), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        findViewById(R.id.btn_app_usage).setOnClickListener(v ->
                startActivity(new Intent(this, AppUsageActivity.class))
        );
        findViewById(R.id.btn_device_power_info).setOnClickListener(v ->
                startActivity(new Intent(this, DevicePowerInfoActivity.class))
        );
        findViewById(R.id.btn_system_control).setOnClickListener(v ->
                startActivity(new Intent(this, SystemControlActivity.class))
        );

        findViewById(R.id.btn_parental_control).setOnClickListener(v ->
                startActivity(new Intent(this, ParentalControlActivity.class))
        );

        findViewById(R.id.btn_software_update).setOnClickListener(v ->
                startActivity(new Intent(this, SoftwareUpdateActivity.class))
        );

        // Start quiet-hours foreground service
        startService(new Intent(this, UsageBlockerService.class));
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 每次resume时检查是否在禁用时间段内
        checkBlockTime();
    }

    private void checkBlockTime() {
        // 检查是否在禁用时间段内
        if (blockTimeChecker.isCurrentTimeBlocked()) {
            // 检查是否已经临时解锁
            if (!parentalControlRepository.isTemporarilyUnlocked()) {
                // 需要密码验证
                Intent intent = new Intent(this, PasswordVerifyActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        } else {
            // 不在禁用时间段，清除临时解锁状态
            parentalControlRepository.clearTemporaryUnlock();
        }
    }
}